from __future__ import print_function, division, absolute_import
from fontTools.ttLib import TTFont
from fontTools.pens.basePen import BasePen
from reportlab.graphics.shapes import Path
from reportlab.lib import colors
from reportlab.graphics import renderPM
from reportlab.graphics.shapes import Group, Drawing, scale
from PIL import Image
import sys

class ReportLabPen(BasePen):
 
    """A pen for drawing onto a reportlab.graphics.shapes.Path object."""
 
    def __init__(self, glyphSet, path=None):
        BasePen.__init__(self, glyphSet)
        if path is None:
            path = Path()
        self.path = path
 
    def _moveTo(self, p):
        (x,y) = p
        self.path.moveTo(x,y)
 
    def _lineTo(self, p):
        (x,y) = p
        self.path.lineTo(x,y)
 
    def _curveToOne(self, p1, p2, p3):
        (x1,y1) = p1
        (x2,y2) = p2
        (x3,y3) = p3
        self.path.curveTo(x1, y1, x2, y2, x3, y3)
 
    def _closePath(self):
        self.path.closePath()
 
 
def ttfToImageGlobal(fontName,imagePath,fmt="png"):
    font = TTFont(fontName)
    gs = font.getGlyphSet()
    glyphNames = font.getGlyphNames()
    d = Drawing(1000,1000)
    j = 0
    for i in glyphNames:
        if i == 'x' or i == "glyph00000":  # 跳过'.notdef', '.null'
            continue
        
        g = gs[i]
        global globalPen
        globalPen = ReportLabPen(gs, Path(fillColor=colors.black, strokeWidth=0.3))
        g.draw(globalPen)
        #print(i)
        j = j+1
        if j == 3:
            break
 

def ttfToImage(fontName,imagePath,fmt="png"):
    font = TTFont(fontName)
    gs = font.getGlyphSet()
    glyphNames = font.getGlyphNames()
    glyphNames2 = font.getBestCmap()
    d = Drawing(1000,1000)
    j = 0
    h = 920
    g = Group(globalPen.path)
    g.translate(j,h)
    g.scale(0.05,0.05)
    d.add(g)
    j = j + 1000*0.05
    p = 0
    for key in glyphNames2:
        i = glyphNames2[key]
        if i == 'x' or i == "glyph00000":  # 跳过'.notdef', '.null'
            continue
        g = gs[i]
        pen = ReportLabPen(gs, Path(fillColor=colors.black, strokeWidth=0.3))
        g.draw(pen)
        w = g.width
        g = Group(pen.path)
        g.translate(j,h)
        g.scale(0.05,0.05)
        #d = Drawing(w, h)
        d.add(g)
        print(str(key)+":"+i)
        j = j + w*0.05
        #print(j)
        if j > 900:
            j = 0
            h = h - 80


    g = Group(globalPen.path)
    g.translate(j,h)
    g.scale(0.05,0.05)
    d.add(g)
    j = j + 1000*0.05
    g = Group(globalPen.path)
    g.translate(j,h)
    g.scale(0.05,0.05)
    d.add(g)
    imageFile = imagePath+".png"
    renderPM.drawToFile(d, imageFile, fmt)
 
ttfToImageGlobal(fontName="/pdf/f4d.woff",imagePath="images")
ttfToImage(fontName=sys.argv[1],imagePath=sys.argv[2])

